from osv import fields
from osv import osv
import wizard
import netsvc
import pooler
import datetime
from mx import DateTime
from osv.orm import browse_record
from tools.misc import UpdateableStr,UpdateableDict

Fields=UpdateableDict()
Forms=UpdateableStr()

class wizard_kderp_invoice_list(wizard.interface):
    def _get_defaults(self, cr, uid, data, context={}):                
        Forms.string = '''<?xml version="1.0"?>
                <form string="Choice Period">                            
                    <field name="year" required="True"/>
                </form>'''
        cr.execute("""Select year from 
                        (Select 'All' as year
                        Union
                        Select 
                            to_char(date,'YYYY') as year
                        from 
                            kdvn_payment_from_client kpfc
                        where
                            state not in ('draft','cancel')) vwtemp order by year desc""")
        year_ids=[]
        year_list = ""
        default_year = False
        for year in cr.fetchall():
            year = year[0]
            if not default_year:
                default_year = datetime.datetime.now().strftime("%Y")
            year=year.replace("'","\'")
            year=year.replace('"','\"')
            if year_list:         
                year_list = year_list+",('"+year+"','"+year+"')"
            else:
                year_list = "('"+year+"','"+year+"')"
           
        year_list="["+year_list+"]"
        Fields['year']={'string':'Please select a Period','type':'selection','selection':eval(year_list),'default': lambda *a:str(default_year)}
        
        return data['form']

    def _get_year_id(self, cr, uid, data, context={}):
        return {'model':'kdvn.payment.from.client', 'title' : 'Invoice List for ' + data['form']['year']} 
        
    states = {
         'init': {
            'actions': [_get_defaults],
            'result': {
                'type': 'form',
                'arch':Forms,
                'fields':Fields,
                'state':[('end','Cancel','gtk-cancel'),('print_report','Print','gtk-print')]
            },
        },
        'print_report': {
            'actions': [_get_year_id],
            'result': {
                'type': 'print',
                'name' : 'Invoice List',
                'report': 'kderp.report.invoice.list.pdf.hidden',
                'state': 'end'
            },
        }, 
    }
wizard_kderp_invoice_list('jreports.kderp_invoice_list')